package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class CustomLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Around("@annotation(customLogin)")
    public Object loginAspect(ProceedingJoinPoint point, CustomLogin customLogin) {
        try {
            // 获取请求对象，并转化为ServletRequestAttributes
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader("token");
            // 判断是否需要登录
            UserInfoVo userInfoVo = null;
            if (StringUtils.hasText(token)) {
                userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
                if (userInfoVo != null) {
                    // 将用户信息存储到请求头中
                    AuthContextHolder.setUserId(userInfoVo.getId());
                    AuthContextHolder.setUsername(userInfoVo.getNickname());
                }
            }
            if (customLogin.required() && userInfoVo == null) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            return point.proceed();
        } finally {
            AuthContextHolder.removeUserId();
            AuthContextHolder.removeUsername();
        }
    }
}
